const { ap, wechatApi } = require('./utils');
const model = require('./model');
const moment = require('moment');
const Sequelize = require('sequelize');
const { Op } = Sequelize;

const schedule = require('node-schedule');

// 0点清空库存
schedule.scheduleJob('0 0 0 * * *', async function() {
    console.log('[定时任务] 清空库存', moment().format('YYYY-MM-DD HH:mm:ss'));

    await model.BistroGoods.update({
        sales: 0,
        monthSales: 0,
    }, {
        where: {},
        // where: {
        //     sales: {
        //         [Op.ne]: 0,
        //     }
        // },
    }).catch(console.error)

    // 月销量
    await model.BistroGoodsTrack.findAll({
        attributes: [
            'goodsId',
            // 销量合计
            [Sequelize.fn('sum', Sequelize.col('sales')), 'sales'],
        ],
        where: {
            createTime: {
                [Op.gte]: moment().subtract(1, 'months').format('YYYY-MM-DD 00:00:00'),
                [Op.lte]: moment().format('YYYY-MM-DD'),
            }
        },
        group: 'goodsId',
    }).then(async res => {
        if (res) {
            ap.queue(res, async (item) => {
                await model.BistroGoods.update({
                    monthSales: Number(item.sales),
                }, {
                    where: {
                        id: item.goodsId,
                    }
                }).catch(console.error)
            })
        }
    }).catch(console.error)
});


// 秒->分->时->天->月->年
schedule.scheduleJob('0 0 * * * *', async function() {
    console.log('[定时任务] 启动');
    try {
        await subscribeMessage();

    } catch (e) {
        console.error('[定时任务] 执行失败', e);
    }
});


// 给消息订阅用户发送消息
async function subscribeMessage() {

    console.log('[定时任务] 发送订阅消息');

    const taskList = await model.BistroSubscribeMessage.findAll({
        where: {
            sendState: 0,
            createTIme: {
                // 查询两个小时前的
                [Op.lte]: moment().add(-2, 'h').format('YYYY-MM-DD HH:mm:ss'),
            },
        }
    })

    await ap.queue(taskList, async (item) => {
        const order = await model.BistroOrder.findOne({
            where: {
                id: item.data.orderId,
            },
        })

        // 订单已评论
        if (!order || order.isComment == 1) {
            item.sendState = 3;
        }
        // 提醒用户评论
        else {
            try {
                const sendResult = await wechatApi.miniProgram.send(item.data.sendData);

                item.sendState = 1;
                item.sendResult = sendResult;
            } catch (e) {
                item.sendState = 2;
                item.sendResult = e;
                console.log(e);
            }

            item.sendTime = new Date();
        }

        await item.save();
    })
}